import 'dart:math';

import 'package:flutter/material.dart';
import 'package:fluttertoast/fluttertoast.dart';
import 'package:schoollifedemo/business/school/viewmodel/announcement_detail_page_viewmodel.dart';
import 'package:schoollifedemo/commonwidget/common_base_page.dart';
import 'package:schoollifedemo/commonwidget/error_widget.dart';
import 'package:schoollifedemo/commonwidget/loading_widget.dart';
import 'package:schoollifedemo/commonwidget/text_widget_with_overflow.dart';
import 'package:schoollifedemo/entity/Entity.dart';

class AnnouncementDetailPage extends BaseStatefulPage {
  final String? base64Url;
  final String? base64MainTitle;

  const AnnouncementDetailPage({Key? key, this.base64Url, this.base64MainTitle})
      : super(key: key);

  @override
  State<StatefulWidget> createState() {
    return _AnnouncementDetailPageState();
  }
}

class _AnnouncementDetailPageState
    extends BasePageState<AnnouncementDetailPage> {
  final AnnouncementDetailPageViewModel _viewModel =
      AnnouncementDetailPageViewModel();
  String? _title;

  @override
  void initState() {
    _viewModel.init();
    _viewModel
        .getChannelService()
        .getCommonChannelFunc()
        ?.decodeBase64(widget.base64Url)
        .asStream()
        .listen((event) {
      _viewModel.pullWebUrl(url: event ?? '');
    });
    _viewModel
        .getChannelService()
        .getCommonChannelFunc()
        ?.decodeBase64(widget.base64MainTitle)
        .asStream()
        .listen(
      (title) {
        _title = title;
      },
    );
    super.initState();
  }

  @override
  void dispose() {
    _viewModel.dispose();
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: Container(
        color: Colors.white,
        child: Column(
          children: [
            Container(
              margin: EdgeInsets.only(
                left: 10,
                right: 10,
                top: MediaQuery.of(context).padding.top,
              ),
              child: Row(
                children: [
                  GestureDetector(
                    onTap: () {
                      _viewModel.backPage(context);
                    },
                    child: Container(
                      margin: const EdgeInsets.only(left: 15),
                      child: const Icon(Icons.arrow_back_ios_outlined),
                    ),
                  ),
                  Expanded(
                    child: TextWidgetWithOverflow(
                      _title,
                      fontSize: 28,
                      insideColor: Colors.transparent,
                      textAlign: TextAlign.left,
                    ),
                  ),
                ],
              ),
            ),
            StreamBuilder(
              stream: _viewModel.loadingState,
              initialData: CommonLoadingState.loading,
              builder: (buildContext, snapshot) {
                final state = snapshot.data as CommonLoadingState?;
                switch (state) {
                  case CommonLoadingState.loading:
                    return Expanded(child: _loadingWidget());
                  case CommonLoadingState.successTypeOne:
                  case CommonLoadingState.successTypeTwo:
                    return Expanded(child: _commonBody());
                  default:
                    return Expanded(child: _errorWidget());
                }
              },
            )
          ],
        ),
      ),
    );
  }

  Widget _commonBody() {
    final contentCount = _viewModel
            .schoolAnnouncementDetailResp?.detailEntity?.contentList?.length ??
        0;
    final imgCount = _viewModel
            .schoolAnnouncementDetailResp?.detailEntity?.imgList?.length ??
        0;
    int imgIndex = 0;
    int contentIndex = 0;

    return Container(
      margin: const EdgeInsets.only(left: 20, right: 20, bottom: 30),
      child: ListView(
        physics: const BouncingScrollPhysics(),
        children: [
          TextWidgetWithOverflow(
            _viewModel.schoolAnnouncementDetailResp?.detailEntity?.title,
            insideColor: Colors.transparent,
            maxLine: 5,
            width: double.infinity,

            fontSize: 26,
          ),
          TextWidgetWithOverflow(
            _viewModel.schoolAnnouncementDetailResp?.detailEntity?.time,
            insideColor: Colors.transparent,
            maxLine: 1,
            width: double.infinity,
            textAlign: TextAlign.left,
            fontSize: 16,
          ),
          TextWidgetWithOverflow(
            _viewModel.schoolAnnouncementDetailResp?.detailEntity?.author,
            insideColor: Colors.transparent,
            maxLine: 1,
            width: double.infinity,
            textAlign: TextAlign.left,
            fontSize: 16,
          ),
          ListView.separated(
            physics: const NeverScrollableScrollPhysics(),
            shrinkWrap: true,
            itemBuilder: (buildContext, index) {
              // if (index % 2 == 0) {
              //   return _textWidget(
              //       text: _viewModel.schoolAnnouncementDetailResp?.detailEntity
              //           ?.contentList?[contentIndex++]);
              // } else {
              //   return _imgWidget(
              //       url: _viewModel.schoolAnnouncementDetailResp?.detailEntity
              //           ?.contentList?[imgIndex]);
              // }
              if (_viewModel.schoolAnnouncementDetailResp?.detailEntity
                      ?.contentList?[index]
                      ?.startsWith('http') ==
                  true) {
                return _imgWidget(
                    url: _viewModel.schoolAnnouncementDetailResp?.detailEntity
                        ?.contentList?[index]);
              } else {
                return _textWidget(
                    text: _viewModel.schoolAnnouncementDetailResp?.detailEntity
                        ?.contentList?[index]);
              }
            },
            separatorBuilder: (buildContext, index) {
              return Container(
                height: 10,
              );
            },
            itemCount: contentCount + imgCount,
          ),
        ],
      ),
    );
  }

  Widget _imgWidget({String? url}) {
    return Container(
      margin: const EdgeInsets.only(left: 10, right: 10),
      child: ClipRRect(
        borderRadius: BorderRadius.circular(20),
        child: Image.network(
          url ?? '',
        ),
      ),
    );
  }

  Widget _textWidget({String? text}) {
    return TextWidgetWithOverflow(
      text,
      fontSize: 16,
      paddingLeft: 20,
      paddingRight: 20,
      paddingTop: 15,
      paddingBottom: 15,
      maxLine: 50,
      textAlign: TextAlign.left,
    );
  }

  Widget _errorWidget() {
    return Center(
      child: Container(
        color: Colors.white,
        child: CommonErrorWidget(
          '错误重试',
          onButtonClick: () async {},
        ),
      ),
    );
  }

  Widget _loadingWidget() {
    return Center(
      child: Container(
        color: Colors.white,
        child: const LoadingWidget(),
      ),
    );
  }
}
